package com.hoperun.udpbroadcast.slice;

import com.hoperun.udpbroadcast.ActivityTools;
import com.hoperun.udpbroadcast.ResourceTable;
import com.hoperun.udpbroadcast.broadcast.BroadcastUtils;
import com.hoperun.udpbroadcast.broadcast.Config;
import com.hoperun.udpbroadcast.broadcast.UdpBroadcastClient;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.TextField;
import ohos.utils.zson.ZSONObject;

public class LightAbilitySlice extends AbilitySlice {
    Config config;
    TextField lightEdit,timeEdit;
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_light);
        config = Config.parseIntent(intent);
        findComponentById(ResourceTable.Id_nextBtn).setClickedListener(this::onClickNext);
        findComponentById(ResourceTable.Id_send_light_btn).setClickedListener(this::onSendBtn);

        lightEdit= (TextField) findComponentById(ResourceTable.Id_light_edit);
        timeEdit= (TextField) findComponentById(ResourceTable.Id_time_edit);

    }

    private void onSendBtn(Component component) {
        int light = BroadcastUtils.parseInt((lightEdit));
        int time = BroadcastUtils.parseInt(timeEdit);
        light = Math.max(10,Math.min(light,100));
        time = Math.max(1,Math.min(time,5000));

        ZSONObject json = new ZSONObject();
        json.put("lightness", String.valueOf(light));
        json.put("time", String.valueOf(time));
        UdpBroadcastClient client = new UdpBroadcastClient();
        client.setAddress(config.getBroadcastIp(), config.getBroadcastPort());
        client.send(json.toString());
    }

    private void onClickNext(Component component) {
        ActivityTools.changePage(this,new EnviromentAbilitySlice(),config.createIntent());
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
